import { useEffect, useState } from "react";
import { Form, Input, Button, MessagePlugin, Select, Table } from "tdesign-react";
import { DesktopIcon, FileExportIcon, FileImportIcon, LockOnIcon, SearchIcon } from "tdesign-icons-react";
import type { FormProps } from "tdesign-react";
import "./index.scss"
import { useNavigate } from "react-router-dom";
import PageWrapper from "../../../components/PageWrapper";
import { Switch } from "../../../components";
import usePagination from "../../../hooks/use-paging";
import { HCommonProduct } from "../../../api/modules/product";
import { HProduct } from "./api";
import { PageResult, Product, CategoryItem } from "./api/api.interface";
import AddProduct from "./components/add-product";


/**
 * 商品列表
 * @returns 
 */
const ProductListComponent = () => {
  const [tableData, setTableData] = useState<Product[]>([]);
  const { currentPage, total, setTotal, goToPage } = usePagination({
    pageSize: 100,
    currentPage: 1,
    total: 0,
    loadData() {
      console.log('当前页码')
      queryProductList();
    },
  });

  useEffect(() => {
    initFilterSelectOption();
    queryProductList();
  }, [])

  // 弹框visible
  const [dialogVisible, setDialogVisible] = useState({
    addProduct: false
  })

  const [formData, setFormData] = useState({
    keyword: '',
    category: ''
  });

  const [filterOptions, setFilterOptions] = useState<{
    category: Array<{
      label: string;
      value: string;
    }>
  }>({
    category: []
  })

  /**
   * 初始化搜索选择项
   */
  const initFilterSelectOption = () => {
    HCommonProduct.queryProductCategoryList<CategoryItem[]>('查询类别列表').then(data => {
      const options = data.map(itm => {
        return {
          label: itm.name,
          value: itm.id
        }
      });
      setFilterOptions({
        ...filterOptions,
        category: options
      })
    });
  }

  /**
   * 查询数据列表
   */
  const queryProductList = async () => {
    const products = await HProduct.queryProductList<PageResult<Product>>('获取商品列表', {
      keyword: formData.keyword,
      page: currentPage,
      pageSize: 100
    });
    setTotal(products.total);
    setTableData(products.list || [])
  }

  const onInputChange = (value: string) => {
    setFormData({
      ...formData,
      keyword: value
    });
  }

  /**
   * 选择切换
   * @param type 
   * @param value 
   */
  const onSelectChange = (type: string, value: string) => {
    setFormData({
      ...formData,
      [type]: value
    });
  }

  /**
   * 状态切换
   * @param value 
   * @returns 
   */
  const useStateChange = (value: boolean) => {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log(value);
        resolve(null);
      }, 1000);
    })
  }

  /**
   * 搜索事件
   */
  const onSearch = () => {
    goToPage(0);
  }

  /**
   * 显示弹框
   * @param name 
   */
  const onDialogShow = (name: string) => {
    const newData = {
      ...dialogVisible,
      [name]: true
    }
    setDialogVisible(newData);
  }

  /**
   * 弹框关闭
   * @param name 
   */
  const onDialogClose = (name: string) => {
    const newData = {
      ...dialogVisible,
      [name]: false
    }
    setDialogVisible(newData);
  }

  return (
    // <div>商品列表</div>
    <PageWrapper title="商品列表" useBack useFullScreen>
      <div className="product-list">
        {/* 筛选 */}
        <div className="table-filter">
          <Form layout='inline'>
            <Form.FormItem name="name">
              <Input placeholder="商品名称" onChange={onInputChange} />
            </Form.FormItem>
            <Form.FormItem name="password">
              <Select
                value={formData.category}
                placeholder="商品类别"
                clearable
                options={filterOptions.category}
                onChange={(v) => onSelectChange('category', v)}
              />
            </Form.FormItem>
            <Form.FormItem className="filter-action">
              <Button size="medium" icon={<SearchIcon />} onClick={onSearch}>搜索</Button>
              <Button size="medium" variant="outline">重置</Button>
            </Form.FormItem>
          </Form>
        </div>

        {/* 工具 */}
        <div className="table-tools">
            <Button variant="outline" theme='primary' onClick={() => onDialogShow('addProduct')}>新增</Button>
            <Button variant="outline">删除</Button>
            <Button variant="outline" icon={<FileImportIcon />}>导出</Button>
            <Button variant="outline" icon={<FileExportIcon />}>导出</Button>
          <Switch
            asyncChange={useStateChange}
            openSlot={
              <span>启用</span>
            }
            closeSlot={
              <span>禁用</span>
            }
          >
            
          </Switch>
        </div>

        {/* 表格内容 */}
        <div className="table-content">
              <Table
                data={tableData}
                columns={[
                  { colKey: 'name', title: '商品名称', fixed: 'left', width: '130' },
                  {
                    colKey: 'image',
                    title: '图片',
                    width: '100',
                    cell: ({ row }) => {
                      return <div className="image-box">
                        <img className="product-img" src="https://img.yanjiuhome.com/litpic/litpic_4231.png"></img>
                      </div>
                    }
                  },
                  { colKey: 'barcode', title: '编码', width: '100', ellipsis: true },
                  { colKey: 'price', title: '销售价', width: '100' },
                  { colKey: 'cost_price', title: '进货价', width: '100' },
                  { colKey: 'unit', title: '单位', width: '100' },
                  { colKey: 'inventory_quantity', title: '库存数量', width: '100' },
                  { colKey: 'status',title: '状态' },
                  { colKey: 'create_time', title: '创建时间', ellipsis: true },
                  { colKey: 'create_user', title: '创建人', ellipsis: true },
                  { colKey: 'update_time', title: '修改时间' },
                  { colKey: 'handle', fixed: 'right', width: '160', title: '操作', cell: ({ row }) => {
                      return <div className="handle-box">
                        <Button theme="primary" variant="text">查看</Button>
                        <Button variant="text">编辑</Button>
                        <Button theme="default" variant="text">删除</Button>
                      </div>
                    } },
                ]}
                tableLayout="fixed"
                maxHeight="600"
                rowKey="index"
                rowClassName={({ rowIndex }) => `${rowIndex}-class`}
                cellEmptyContent={'-'}
                // 与pagination对齐
                pagination={{
                  defaultCurrent: currentPage,
                  defaultPageSize: 50,
                  total: total,
                  showJumper: true,
                  onChange(pageInfo) {
                    console.log(pageInfo, 'onChange pageInfo');
                  },
                  onCurrentChange(current, pageInfo) {
                    console.log(current, pageInfo, 'onCurrentChange current');
                  },
                  onPageSizeChange(size, pageInfo) {
                    console.log(size, pageInfo, 'onPageSizeChange size');
                  },
                }}
                onPageChange={(pageInfo) => {
                  console.log(pageInfo, 'onPageChange');
                }}
                onRowClick={({ row, index, e }) => {
                  console.log('onRowClick', { row, index, e });
                }}
              />
        </div>
      </div>

      {/* 新增商品弹框 */}
      <AddProduct visible={dialogVisible.addProduct} onClose={() => onDialogClose('addProduct')}></AddProduct>
    </PageWrapper>
  )
};


export default ProductListComponent;